from flask import Flask, render_template, Response
import cv2
import imutils
from imutils.video import VideoStream
from imutils.video import FPS
from imutils.video import WebcamVideoStream
import numpy as np
import os
import time
import json
import requests
import base64
from flask_cors import *
protoPath = os.path.sep.join(['face_detection_model', "deploy.prototxt"])
modelPath = os.path.sep.join(['face_detection_model',"res10_300x300_ssd_iter_140000.caffemodel"])

app = Flask(__name__)
CORS(app, supports_credentials=True)
class VideoCamera(object):
    def __init__(self):
        self.video = WebcamVideoStream(src=0).start()
    def get_frame(self):
        detector = cv2.dnn.readNetFromCaffe(protoPath, modelPath)
        frame = self.video.read()
        frame = imutils.resize(frame, width=600)
        (h, w) = frame.shape[:2]
        # construct a blob from the image
        imageBlob = cv2.dnn.blobFromImage(
            cv2.resize(frame, (300, 300)), 1.0, (300, 300),
            (104.0, 177.0, 123.0), swapRB=False, crop=False)
        detector.setInput(imageBlob)
        detections = detector.forward()
        for i in range(0, detections.shape[2]):
            confidence = detections[0, 0, i, 2]
            if confidence > 0.8:
                box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
                (startX, startY, endX, endY) = box.astype("int")
                t = time.time()
                fileName ="./static/images/"+str(round(t))+"1.jpg"
                cv2.imwrite(fileName, frame)
              
                cv2.rectangle(frame, (startX, startY), (endX, endY),
                              (0, 0, 255), 2)
        ret, jpeg = cv2.imencode('.jpg', frame )
        return jpeg.tobytes()

@app.route('/')  
def index():

    return render_template('index.html')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')  
def video_feed():
    return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame')



def sort_file_by_time():
    file_path = 'C:\\Users\\game\\PycharmProjects\\flask_opencv\\static\\images'
    files = os.listdir(file_path)
    if not files:
        return
    else:
        files = sorted(files, key=lambda x: os.path.getmtime(os.path.join(file_path, x)))  
        return files

@app.route('/face_img1')
def face_img1():
    img_name=sort_file_by_time()[-1]
    s = "http://[2001:da8:a80a:3003:d95f:90a7:2ce3:ae14]:8099/static/images/"+img_name

    return (s)

@app.route('/face_img2')
def face_img2():
    img_name = sort_file_by_time()[-1]
    s = "http://[2001:da8:a80a:3003:d95f:90a7:2ce3:ae14]:8099/static/images/"+img_name
   

    return (s)
@app.route('/face_img3')
def face_img3():
    img_name = sort_file_by_time()[-1]
    s = "http://[2001:da8:a80a:3003:d95f:90a7:2ce3:ae14]:8099/static/images/" + img_name
   

@app.route('/blacklist_faceimg')
def get_blacklist_face():
    img_name = sort_file_by_time()[-1]
    img_name='./static/images/'+img_name
    img_file = open(img_name, 'rb')  # 二进制打开图片文件
    img_b64encode = base64.b64encode(img_file.read())
    params_face = {"image": img_b64encode, "image_type": 'BASE64', "group_id_list": "123"}
    face_name = requests.post(url_search, data=params_face, headers=headers)
    all_str = json.loads(face_name.text)
    if all_str["error_msg"] == 'SUCCESS':
        print(all_str["result"]['user_list'][0]['user_id'])
        s = "http://[2001:da8:a80a:3003:d95f:90a7:2ce3:ae14]:8099/"+img_name
        return  s
    else:
        s="http://[2001:da8:a80a:3003:d95f:90a7:2ce3:ae14]:8099/static/images/no.jpg"
        return s

if __name__ == "__main__":
    app.run(port=8099,debug=True)